package tw.asap.plus.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import jp.wasabeef.recyclerview.animators.FadeInRightAnimator;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.request.LocationBean;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.MerchantService;
import tw.asap.plus.ui.activity.GeoActivity;
import tw.asap.plus.ui.activity.MainActivity;
import tw.asap.plus.ui.activity.SearchActivity;
import tw.asap.plus.ui.adapter.HomeAdapter;
import tw.asap.plus.utils.Toaster;


/**
 * Description:
 * Created:      [15/10/21]
 * Author:       [Yang]
 **/
public class HomeFragment extends Fragment implements View.OnClickListener, MainActivity.LocationListener {

    @InjectView(R.id.rv_base_list_fragment)
    public RecyclerView recyclerView;
    @InjectView(R.id.srl_base_list_fragment)
    public SwipeRefreshLayout swipeRefreshLayout;


    @InjectView(R.id.ll_navigation_left)
    View leftNavigation;

    @InjectView(R.id.ll_navigation_right)
    View rightNavigation;

    @InjectView(R.id.tv_naviation_title)
    TextView midNavigation;
    @InjectView(R.id.extra_layout)
    FrameLayout extraLayout;
    @InjectView(R.id.layout_root)
    LinearLayout layoutRoot;
    @InjectView(R.id.progress_location)
    LinearLayout progressLocation;



    private View view;
    private int currentPage;
    private HomeAdapter adapter;
    private int pageSize = 10;
    private boolean isLoading;
    private boolean hasMore = true;
    private tw.asap.plus.entity.LocationBean mLocation;
    private boolean hasLoadOnErrorLocation;

    public static Fragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (swipeRefreshLayout != null)
            swipeRefreshLayout.setRefreshing(false);
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_main, null);
        } else {
            if (view.getParent() != null)
                ((ViewGroup) view.getParent()).removeView(view);
        }
        ButterKnife.inject(this, view);
        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        ((MainActivity) getActivity()).registerLocationListener(this);
    }


    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ((MainActivity) getActivity()).unRegisterLocationListener(this);
    }

    ArrayList testList = new ArrayList();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rightNavigation.setOnClickListener(this);
        swipeRefreshLayout.setColorSchemeResources(R.color.palette_red);
        swipeRefreshLayout.setOnRefreshListener(() -> reload(false));
    }

    private void initRecyclerView(ShopIndex data) {
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        adapter = new HomeAdapter(getActivity(), recyclerView, data);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new FadeInRightAnimator());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (mLayoutManager.findLastVisibleItemPosition() + 1 == testList.size() - 1
                        && testList.size() > pageSize - 1 && !isLoading && hasMore) {
                    Log.d("onScrolled", "end");
                    loadMore();
                }
            }
        });
    }


    public void reload(boolean isBackground) {
        if (swipeRefreshLayout != null && !isBackground)
            swipeRefreshLayout.setRefreshing(true);
        currentPage = 0;

        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<ShopIndex>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<ShopIndex>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);
                String lat = "0";
                String lng = "0";
                if (mLocation != null) {
                    lat = String.valueOf(mLocation.latitude);
                    lng = String.valueOf(mLocation.longitude);
                }
                ResponseDataWrapper<ShopIndex> responseDataWrapper = service.getIndexInfo(new LocationBean(lat, lng));
                subscriber.onNext(responseDataWrapper);
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<ShopIndex>>() {
                               @Override
                               public void onCompleted() {
                                   adapter.notifyDataSetChanged();
                               }

                               @Override
                               public void onError(Throwable e) {
                                   if (swipeRefreshLayout != null && !isBackground) {
                                       swipeRefreshLayout.setRefreshing(false);
                                   }
                                   if (e.getMessage().equals(ConstValue.INTERNET_ERROR)) {
                                       initExtraLayout(2);
                                   }
                                   Toaster.s(getActivity(), e.getMessage());
                               }

                               @Override
                               public void onNext(ResponseDataWrapper<ShopIndex> responseDataWrapper) {
                                   if (swipeRefreshLayout != null && !isBackground)
                                       swipeRefreshLayout.setRefreshing(false);
                                   if (responseDataWrapper.respcd.equals(ConstValue.RESPCD)) {
                                       initRecyclerView(responseDataWrapper.data);
                                   }
                               }
                           }

                );
    }


    public void loadMore() {

    }

    @Override
    public void onPause() {
        super.onPause();
        if (swipeRefreshLayout != null) {
            Log.d("onPause", "swipeRefreshLayout！＝null");
            swipeRefreshLayout.setRefreshing(false);
            swipeRefreshLayout.destroyDrawingCache();
            swipeRefreshLayout.clearAnimation();
        }
    }

    public void initExtraLayout(int state) {
        swipeRefreshLayout.setVisibility(View.GONE);
        extraLayout.setVisibility(View.VISIBLE);
        switch (state) {
            case 0://loading
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(getActivity()).inflate(R.layout.layout_loading, extraLayout);
                break;
            case 1://noData
                swipeRefreshLayout.setVisibility(View.GONE);
                View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_collection, extraLayout);
                ((ImageView) emptyView.findViewById(R.id.icon)).setImageResource(R.drawable.icon_record_empty);
                ((TextView) emptyView.findViewById(R.id.empty_hint)).setText(getString(R.string.no_order_within_month));

                break;
            case 2://noNetwork
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(getActivity()).inflate(R.layout.layout_nonetwork, extraLayout);
                extraLayout.setOnClickListener(v -> reload(true));
                break;
        }

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_navigation_right:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
        }
    }

    @OnClick(R.id.tv_naviation_title)
    protected void onLocationClick() {
        Intent locateIntent = new Intent(getActivity(), GeoActivity.class);
//        locateIntent.putExtra("LOCATION", mLastLocation);
        getActivity().startActivityForResult(locateIntent, MainActivity.REQUEST_FOR_LOCATION);
    }


    @Override
    public void onGetLocationSuccess() {
        progressLocation.setVisibility(View.GONE);
        midNavigation.setVisibility(View.VISIBLE);
        mLocation = ((MainActivity) getActivity()).getLastLocation();
        if(mLocation.address !=null && mLocation.address.contains("中国")){
            mLocation.address = mLocation.address.replace("中国","");
        }
        if(mLocation.address !=null && mLocation.address.contains("台湾省")){
            mLocation.address = mLocation.address.replace("台湾省","");
        }
        midNavigation.setText(mLocation.address);
        reload(true);
    }

    public void onGetLocationFailed() {
        progressLocation.setVisibility(View.GONE);
        midNavigation.setVisibility(View.VISIBLE);
        midNavigation.setText(getString(R.string.unknow_location));
        if (!hasLoadOnErrorLocation) {
            reload(true);
            hasLoadOnErrorLocation = true;
        }
    }

    @Override
    public void onGetLatLon(tw.asap.plus.entity.LocationBean mLastLocation) {
        this.mLocation = mLastLocation;
    }
}
